package com.example.a28796.beautiful.fragment;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.a28796.beautiful.MainActivity;
import com.example.a28796.beautiful.R;
import com.example.a28796.beautiful.adapter.FirstPageAdapter;
import com.example.a28796.beautiful.adapter.FirstPageMainAdapter;
import com.example.a28796.beautiful.adapter.HeadPagerAdapter;
import com.example.a28796.beautiful.bean.FirstPageBean;
import com.example.a28796.beautiful.bean.FirstPageMainBean;
import com.example.a28796.beautiful.config.NetConfig;
import com.example.a28796.beautiful.configinterface.NetInterface;
import com.example.a28796.beautiful.utils.MyListView;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshExpandableListView;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by 28796 on 2016/8/29.
 */
public class FragmentFirstPage extends Fragment {
    private PullToRefreshListView listView;
    private AnimationDrawable drawable;
    private AnimationDrawable headDrawable;
    private ImageView mPopImage;
    private ListView mListView;
    private MyListView mHeadListView;
    private BaseAdapter itemAdapter;
    private ViewPager mViewPager;
    private List<FirstPageBean.ObjBean.AreasBean> mItemData;
    private BaseAdapter mMainAdapter;
    private List<FirstPageMainBean.ObjBean.ListDataBean> mMainData;
    private PagerAdapter mPagerAdapter;
    private List<ImageView> mImage;
    private ImageView mImageView;
    private int mPosition = 1;
    private int currentPage = 1;
    private boolean isBottom;
    private RollPagerView mRollViewPager;
    private Retrofit mRetrofit,mRetrofit2;
    private NetInterface mNetInterFace,mNetInterFace2;
    private ImageView animImage;
    private TextView animText;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_firstpage,null);
        animImage = (ImageView) view.findViewById(R.id.iv_animation);
        animText = (TextView) view.findViewById(R.id.tv_animation);
         drawable = (AnimationDrawable) animImage.getBackground();
         drawable.start();
        initView(view);
        initData();
        setData();
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                currentPage++;
                isBottom=false;
                getData(currentPage);
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                isBottom = firstVisibleItem+visibleItemCount==totalItemCount;
            }
        });
        return view;
    }

    private void showPopwindow() {
        // 利用layoutInflater获得View
        View view = getActivity().getLayoutInflater().inflate(R.layout.popwindowlayout, null);
        // 下面是两种方法得到宽度和高度 getWindow().getDecorView().getWidth()
        PopupWindow window = new PopupWindow(view,
                WindowManager.LayoutParams.MATCH_PARENT,
               1450);
        // 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
        window.setFocusable(true);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        window.setBackgroundDrawable(dw);
        // 设置popWindow的显示和消失动画
        window.setAnimationStyle(R.style.mypopwindow_anim_style);
        window.showAtLocation(getActivity().findViewById(R.id.layout_pop),
                Gravity.TOP, 0,170);
        Button first = (Button) view.findViewById(R.id.first);

        first.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "hahahaha", Toast.LENGTH_SHORT).show();
            }
        });

    }
    private void setData() {
        mRollViewPager.setAdapter(mPagerAdapter);
        mHeadListView.setAdapter(itemAdapter);
        listView.setMode(PullToRefreshBase.Mode.BOTH);
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                currentPage=1;
                getData(1);
                currentPage++;
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getData(currentPage);
                currentPage++;
            }
        });
        final ILoadingLayout loadingLayoutProxy = listView.getLoadingLayoutProxy();
        listView.setAdapter(mMainAdapter);
    }
    private void initData() {
        getData(1);
        mItemData = new ArrayList<>();
        itemAdapter = new FirstPageAdapter(mItemData,getActivity());
        mImage = new ArrayList<>();
        mPagerAdapter = new HeadPagerAdapter(mImage);
        mMainData = new ArrayList<>();
        mMainAdapter = new FirstPageMainAdapter(mMainData,getActivity());
        //为了防止报错 必须以/结尾   经测试 外网不需要加
        //设置基地址
        mRetrofit = new Retrofit.Builder().baseUrl(NetConfig.FIRST_PAGE_VIEWPAGER)
                //添加转换工厂
                .addConverterFactory(GsonConverterFactory.create()).build();
        mNetInterFace =mRetrofit.create(NetInterface.class);
        final Call<ResponseBody> netData = mNetInterFace.getNetData();
        netData.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if(response.isSuccessful()) {
                    try {
                        final String string = response.body().string();
                        Gson gson = new Gson();
                        final FirstPageBean firstPageBean = gson.fromJson(string, FirstPageBean.class);
                        final List<FirstPageBean.ObjBean.CarouselsBean> carousels = firstPageBean.getObj().getCarousels();
                        for (int i = 0; i <carousels.size() ; i++) {
                            final FirstPageBean.ObjBean.CarouselsBean.CoverBean cover = carousels.get(i).getCover();
                            final String url = cover.getUrl();
                            mImageView  = new ImageView(getActivity());
                            Picasso.with(getActivity()).load(url).into(mImageView);
                            mImage.add(mImageView);
                        }
                        mPagerAdapter.notifyDataSetChanged();
                        final List<FirstPageBean.ObjBean.AreasBean> areas = firstPageBean.getObj().getAreas();
                        Log.i("gaofengFirstPageAdapter", "onResponse1: "+areas.size());
                        mItemData.addAll(areas);
                        Log.i("gaofengFirstPageAdapter", "onResponse2: "+mItemData.size());
                        itemAdapter.notifyDataSetChanged();
                        animImage.setVisibility(View.GONE);
                        animText.setVisibility(View.GONE);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }
    public void getData(final int currentPage){
                        /////////////主界面的listview/////////////
                        mRetrofit2 = new Retrofit.Builder().baseUrl(NetConfig.FIRST_PAGE_DAIFEN)
                                //添加转换工厂
                                .addConverterFactory(GsonConverterFactory.create()).build();
                        mNetInterFace2 =mRetrofit2.create(NetInterface.class);
                        final Call<ResponseBody> netItemData = mNetInterFace2.getNetItemData(currentPage);
                        netItemData.enqueue(new Callback<ResponseBody>() {
                            @Override
                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                try {
                                    final String string1 = response.body().string();
                                    Log.i("gaofeng1", "onResponse: "+string1);
                                    Gson gson = new Gson();
                                    final FirstPageMainBean firstPageMainBean = gson.fromJson(string1, FirstPageMainBean.class);
                                    if(currentPage==1){
                                        mMainData.clear();
                                        mMainAdapter.notifyDataSetChanged();
                                    }
                                    final List<FirstPageMainBean.ObjBean.ListDataBean> listData = firstPageMainBean.getObj().getListData();
                                    mMainData.addAll(listData);
                                    mMainAdapter.notifyDataSetChanged();
                                    listView.onRefreshComplete();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onFailure(Call<ResponseBody> call, Throwable t) {

                            }
                        });
    };
    private void initView(View view) {
        mPopImage = (ImageView) view.findViewById(R.id.iv_pop);
        mPopImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopwindow();
                Log.i("showPopwindow", "onClick:点击了按钮===== ");
            }
        });
        listView = (PullToRefreshListView) view.findViewById(R.id.lv_main_fragment_first);
        View headView = View.inflate(getActivity(),R.layout.head_fragment_first,null);
        mHeadListView = (MyListView) headView.findViewById(R.id.lv_head_fragmentfirst);
        mRollViewPager = (RollPagerView) headView.findViewById(R.id.vp_fragment_first);
        //设置播放时间间隔
        mRollViewPager.setPlayDelay(4000);
        //设置透明度
        mRollViewPager.setAnimationDurtion(500);
        //设置适配器
        //设置指示器（顺序依次）
        //自定义指示器图片
        //设置圆点指示器颜色
        //设置文字指示器
        //隐藏指示器
        //mRollViewPager.setHintView(new IconHintView(this, R.drawable.point_focus, R.drawable.point_normal));
        mRollViewPager.setHintView(new ColorPointHintView(getActivity(), Color.BLUE, Color.WHITE));
        final ListView refreshableView = listView.getRefreshableView();
        refreshableView.addHeaderView(headView);
    }

}
